package com.pf.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.pf.common.constants.SystemConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatis-plus 自动填充功能
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/8/14
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增时，自动填充字段。因为在BaseEntity类中 @TableField注解中value已经映射数据库表字段了，所以这里直接填充实体属性即可
     * 如 @TableField(value = "is_deleted", fill = FieldFill.INSERT)
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String userName = metaObject.getValue("createdBy") != null ? (String) metaObject.getValue("createdBy") : SystemConst.SYSTEM;
        this.setFieldValByName("isDeleted", 0, metaObject);
        this.setFieldValByName("version", 0, metaObject);
        this.setFieldValByName("createdBy", userName, metaObject);
        this.setFieldValByName("createdDate", new Date(), metaObject);
        this.setFieldValByName("updatedBy", userName, metaObject);
        this.setFieldValByName("updatedDate", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userName = metaObject.getValue("createdBy") != null ? (String) metaObject.getValue("createdBy") : SystemConst.SYSTEM;
        this.setFieldValByName("updatedBy", userName, metaObject);
        this.setFieldValByName("updatedDate", new Date(), metaObject);
    }
}
